package com.sailfish.springbootdemo.service.db2.impl;

import com.alibaba.fastjson.JSONObject;
import com.sailfish.springbootdemo.pojo.Result;
import com.sailfish.springbootdemo.pojo.db1.EmailRecord;
import com.sailfish.springbootdemo.pojo.db2.MailAdGroup;
import com.sailfish.springbootdemo.pojo.db2.MailAddress;
import com.sailfish.springbootdemo.pojo.db2.MailDepartment;
import com.sailfish.springbootdemo.pojo.db2.MailGroupParam;
import com.sailfish.springbootdemo.service.db1.EmailRecordService;
import com.sailfish.springbootdemo.service.db2.ThirdApiService;
import com.sailfish.springbootdemo.utils.HttpUtil;
import com.sailfish.springbootdemo.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class ThirdApiServiceImpl implements ThirdApiService {
    @Value("${personal.config.httpUrl.h3cEmailToken}")
    String h3cEmailToken;
    @Value("${personal.config.httpUrl.h3cEmailSend}")
    String h3cEmailSend;
    @Value("${personal.config.email.account}")
    String account;
    @Value("${personal.config.email.password}")
    String password;
    @Value("${personal.config.email.clientId}")
    String clientId;//租户id
    @Value("${personal.config.email.templateId}")
    String templateId;//模板id

    @Autowired
    private EmailRecordService emailRecordService;

    @Override
    public Result sendMail(String username, String title, String mailContentTitle, String mailContent, String templateCode, List<MailAddress> mailAddressList, Map<String, byte[]> attachments, List<MailAdGroup> mailAdGroupList, List<MailDepartment> mailDepartmentList, List<MailGroupParam> mailGroupParamList, Integer priority, String sendMail) throws Exception {
        log.info("start send mail");
        JSONObject params1 = new JSONObject();
        params1.put("account", account);
        params1.put("password", password);
        log.info("account:" + account);
        log.info("password:" + password);
        String token = "";
        try {
            String res1 = HttpUtil.sendPostJson(h3cEmailToken, params1);
            log.info("url h3cEmailToken:" + h3cEmailToken);
            log.info("get token res:" + res1);
            JSONObject jsonObject = JSONObject.parseObject(res1);
            if (jsonObject.getBoolean("flag")) {
                JSONObject data = jsonObject.getJSONObject("data");
                token = data.getString("token");
            } else {
                String msg = jsonObject.getString("message");
                log.error(msg);
                return ResultUtil.error(500, msg, msg, null);
            }
        } catch (Exception e) {
            log.error("调用接口" + h3cEmailToken + "异常：" + e.getMessage());
            return ResultUtil.error(500, "调用接口" + h3cEmailToken + "异常：" + e.getMessage(), "", null);
        }

        if (StringUtils.isBlank(token)) {
            String msg = "token为空";
            log.error(msg);
            return ResultUtil.error(500, msg, msg, null);
        }
        JSONObject titleParams = new JSONObject();
        titleParams.put("title", title);
        JSONObject contentParams = new JSONObject();
        contentParams.put("link", "");
        contentParams.put("title2", title);
        contentParams.put("user", username);
        contentParams.put("body", mailContent);

        JSONObject params = new JSONObject();
        params.put("msgType", 3);
        params.put("titleParams", titleParams);
        params.put("clientId", clientId);
        log.info("clientId:" + clientId);
        params.put("templateCode", templateId);
        log.info("templateId:" + templateId);
        params.put("contentParams", contentParams);
        params.put("attachments", attachments);
        params.put("mailAddressList", mailAddressList);
        params.put("mailDepartmentList", mailDepartmentList);
        params.put("mailGroupParamList", mailGroupParamList);
        params.put("priority", priority);
        params.put("sendMail", sendMail);
        token = "Bearer " + token;
        try {
            String res = HttpUtil.sendPostJsonToken(h3cEmailSend, params, token);
            log.info("send mail res:" + res);
            JSONObject jsonObject2 = JSONObject.parseObject(res);
            if (jsonObject2.getBoolean("flag")) {

                EmailRecord addEmailRecord = new EmailRecord();
                addEmailRecord.setEmailJson(params.toString());
                addEmailRecord.setEmailResult(1);
                emailRecordService.addEmailRecord(addEmailRecord);
                return ResultUtil.success(null);
            } else {
                String msg = jsonObject2.getString("message");

                EmailRecord addEmailRecord = new EmailRecord();
                addEmailRecord.setEmailJson(params.toString());
                addEmailRecord.setEmailResult(2);
                addEmailRecord.setFailReason(msg);
                emailRecordService.addEmailRecord(addEmailRecord);
                log.error("发邮件出错：" + msg);
                return ResultUtil.error(500, "发邮件出错：" + msg, "send mail error：" + msg, null);
            }
        } catch (Exception e) {
            EmailRecord addEmailRecord = new EmailRecord();
            addEmailRecord.setEmailJson(params.toString());
            addEmailRecord.setEmailResult(2);
            addEmailRecord.setFailReason(e.getMessage());
            emailRecordService.addEmailRecord(addEmailRecord);
            log.error("调用接口" + h3cEmailSend + "异常：" + e.getMessage());
            return ResultUtil.error(500, "调用接口" + h3cEmailSend + "异常：" + e.getMessage(), "", null);
        }

    }
}
